import { computed, defineComponent, onMounted, ref } from "vue";
import { useRoute } from 'vue-router'
import useResizer from "@/hooks/useResizer";
import { ThemeStylesOptions } from "@/types";
import { ElMessage } from 'element-plus'
import styles from "./index.module.less";
import { HTMLRender, MarkDowmEditor, Header, HTMLRenderExposed, ToolTab } from './components'
import { transformHtmlFunc } from './utils'
import { getRecordDetial, uploadFile, createRecord, updataRecord } from './editor.request'
import { getTemplate } from "../resume-template/template.request";

export default defineComponent({
  setup() {
    const route = useRoute()

    const { clientX: codeEditorWidth, resizerRef } = useResizer();

    let mode: 'create' | 'edit' | undefined = 'create'
    let id: string | undefined

    const mdRef = ref()
    const name = ref()
    const styleThemeRef = ref<ThemeStylesOptions>(ThemeStylesOptions.Base)
    const onChange = (mdStr: string) => mdRef.value = mdStr
    const htmlRef = computed(() => transformHtmlFunc(mdRef.value, { theme: styleThemeRef.value }))

    onMounted(async () => {
      if (route.query.id) {
        id = route.query.id as string
        mode = 'edit'
        const { data } = await getRecordDetial(route.query.id as string)
        onChange(data.content)
        name.value = data.name
        styleThemeRef.value = data.theme_style
      }
    })

    onMounted(async () => {
      if (route.query.templateId) {
        mode = 'create'
        const { data } = await getTemplate(route.query.templateId as string)
        onChange(data.content)
        name.value = data.name
        styleThemeRef.value = data.theme_style
      }
    })

    const htmlRenderRef = ref<HTMLRenderExposed>();

    const onExportPDF = () => {
      htmlRenderRef.value?.exportPDF()
    }

    const onChangeStyleTheme = (themeStyle: ThemeStylesOptions) => {
      styleThemeRef.value = themeStyle
    }

    const createCover = async () => {
      const file = await htmlRenderRef.value?.generateCover(name.value)
      if (!file) {
        return
      }
      const formData = new FormData()
      formData.append('file', file)

      const { data: { fileUrl } } = await uploadFile(formData)

      return fileUrl
    }

    const onSave = async () => {
      const fileUrl = await createCover()

      if (!fileUrl) {
        ElMessage.error('封面生成失败')
        return
      }

      if (mode === 'create') {
        const { data: { id: recordId } } = await createRecord({
          name: name.value,
          content: mdRef.value,
          cover: fileUrl,
          theme_style: styleThemeRef.value
        })

        id = recordId
        mode = 'edit'
      }

      if (mode === 'edit' && id) {
        await updataRecord(id, {
          name: name.value,
          content: mdRef.value,
          theme_style: styleThemeRef.value,
          cover: fileUrl
        })
      }

      ElMessage.info('保存成功')

    }

    return () => (
      <div class={styles.editorPage}>
        <Header
          resumeName={name.value}
          resumeNameOnChange={(value: string) => name.value = value}
          styleTheme={styleThemeRef.value}
          onExportPDF={onExportPDF}
          onChangeStyleTheme={onChangeStyleTheme}
          onSave={onSave}
        />
        <div class={styles.main}>
          <div
            class={styles.left}
            style={{ width: codeEditorWidth.value + "px" }}
          >
            <MarkDowmEditor
              value={mdRef.value}
              onChange={onChange}
            />
          </div>
          <div class={styles.resizer} ref={resizerRef}></div>
          <div class={styles.right}>
            <HTMLRender
              ref={htmlRenderRef}
              class={styles.renderContent}
              html={htmlRef.value}
            />
          </div>
        </div>
      </div>
    );
  },
});

